/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.stateless.MRP.ProductionPlan;

import entity.MRP.ProductionPlan.PlannedMonthlyDemand;
import entity.MRP.ProductionPlan.PlannedWeeklyDemand;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import session.stateless.MRP.MaterialRequirement.WeeklyMaterialReqBeanLocal;

/**
 *
 * @author zhozho
 */
@Stateless
public class WeeklyProductionPlanBean implements WeeklyProductionPlanBeanLocal {
    
    @PersistenceContext 
    private EntityManager em;
    @EJB
    private MonthlyProductionPlanBeanLocal monthlyProductionPlanBeanLocal;
    @EJB
    private DailyProductionPlanBeanLocal dailyProductionPlanBeanLocal;
    @EJB
    private WeeklyMaterialReqBeanLocal weeklyMaterialReqBeanLocal;
    
    public List<PlannedWeeklyDemand> createPlannedWeeklyDemands(String month)
    {
        //input format 1/2012
        List<PlannedWeeklyDemand> weeklyDemands = new ArrayList<PlannedWeeklyDemand>();
        int monthNumber = Integer.parseInt(month.substring(0, month.length() - 5));
        int year = Integer.parseInt(month.substring(month.length() - 4));
        List<String> weekList = this.getWeeks(monthNumber, year);
        
        //set monthly demand
        Query q = em.createQuery("SELECT p FROM PlannedMonthlyDemand p WHERE p.monthName=:month");
        q.setParameter("month", month);
        PlannedMonthlyDemand plannedMonthlyDemand = (PlannedMonthlyDemand) q.getSingleResult();
        
        //set working days in week

        int firstDay = 0;
        int lastDay = 0;
        for (int i = 0; i < weekList.size(); ++i)
        {
            PlannedWeeklyDemand p = new PlannedWeeklyDemand();
            p.setPlannedMonthlyDemand(plannedMonthlyDemand);
            
            p.setWeekPeriod(weekList.get(i));
            if (i == 5)
                p.setWeekNumber(new Long(i));
            else p.setWeekNumber(new Long(i+1));
            firstDay = Integer.parseInt(weekList.get(i).substring(0, weekList.get(i).indexOf("/")));
            String temp = weekList.get(i).substring(weekList.get(i).indexOf("/") + 1);
            lastDay = Integer.parseInt(temp.substring(temp.indexOf("-")+1, temp.indexOf("/")));

            p.setNumberOfWorkingDay(new Long(lastDay - firstDay + 1));
            
            //set weekly demand
            Long amtA = Math.round((double) (p.getPlannedMonthlyDemand().getProductionPlanA() * p.getNumberOfWorkingDay()) / (double) p.getPlannedMonthlyDemand().getNumberOfWorkingDays());
            if (p.getPlannedMonthlyDemand().getProductionPlanA() != null)                
                p.setWeeklyDemandA(amtA);
            Long amtB = Math.round((double) (p.getPlannedMonthlyDemand().getProductionPlanB() * p.getNumberOfWorkingDay()) / (double) p.getPlannedMonthlyDemand().getNumberOfWorkingDays());
            if (p.getPlannedMonthlyDemand().getProductionPlanB() != null)
                p.setWeeklyDemandB(amtB);
            Long amtC = Math.round((double) (p.getPlannedMonthlyDemand().getProductionPlanC() * p.getNumberOfWorkingDay()) / (double) p.getPlannedMonthlyDemand().getNumberOfWorkingDays());
            if (p.getPlannedMonthlyDemand().getProductionPlanC() != null)
                p.setWeeklyDemandC(amtC);
            Long amtD = Math.round((double) (p.getPlannedMonthlyDemand().getProductionPlanD() * p.getNumberOfWorkingDay()) / (double) p.getPlannedMonthlyDemand().getNumberOfWorkingDays());
            if (p.getPlannedMonthlyDemand().getProductionPlanD() != null)
                p.setWeeklyDemandD(amtD);
            
            em.persist(p);
            
            weeklyMaterialReqBeanLocal.createWeeklyMaterialReq(p.getId(), amtA, amtB, amtC, amtD);
            
            p.setPlannedDailyDemand(dailyProductionPlanBeanLocal.createPlannedDailyDemands(weekList.get(i)));
            em.flush();
            
            //plannedMonthlyDemand.getListOfPlannedWeeklyDemand().add(p);
            
            weeklyDemands.add(p);
        }
            
            
        return weeklyDemands;
    }
    
    public void updatePlannedWeeklyDemand(Long id)
    {
        //input format 1/2012
        PlannedWeeklyDemand p = em.find(PlannedWeeklyDemand.class, id);
        String week = p.getWeekPeriod();
        int firstDay = Integer.parseInt(week.substring(0, week.indexOf("/")));
        String temp = week.substring(week.indexOf("/") + 1);
        int month = Integer.parseInt(temp.substring(0, temp.indexOf("-")));
        int lastDay = Integer.parseInt(temp.substring(temp.indexOf("-")+1, temp.indexOf("/")));

        //set monthly demand
        
        PlannedMonthlyDemand plannedMonthlyDemand = p.getPlannedMonthlyDemand();
        

        //set weekly demand
        Long amtA = Math.round((double) (p.getPlannedMonthlyDemand().getProductionPlanA() * p.getNumberOfWorkingDay()) / (double) p.getPlannedMonthlyDemand().getNumberOfWorkingDays());
            if (p.getPlannedMonthlyDemand().getProductionPlanA() != null)                
                p.setWeeklyDemandA(amtA);
            Long amtB = Math.round((double) (p.getPlannedMonthlyDemand().getProductionPlanB() * p.getNumberOfWorkingDay()) / (double) p.getPlannedMonthlyDemand().getNumberOfWorkingDays());
            if (p.getPlannedMonthlyDemand().getProductionPlanB() != null)
                p.setWeeklyDemandB(amtB);
            Long amtC = Math.round((double) (p.getPlannedMonthlyDemand().getProductionPlanC() * p.getNumberOfWorkingDay()) / (double) p.getPlannedMonthlyDemand().getNumberOfWorkingDays());
            if (p.getPlannedMonthlyDemand().getProductionPlanC() != null)
                p.setWeeklyDemandC(amtC);
            Long amtD = Math.round((double) (p.getPlannedMonthlyDemand().getProductionPlanD() * p.getNumberOfWorkingDay()) / (double) p.getPlannedMonthlyDemand().getNumberOfWorkingDays());
            if (p.getPlannedMonthlyDemand().getProductionPlanD() != null)
                p.setWeeklyDemandD(amtD);

        em.persist(p);
        
        weeklyMaterialReqBeanLocal.updateWeeklyMaterialReq(p.getId(), amtA, amtB, amtC, amtD);
        
        em.flush();
    }
    
    public List<String> getWeeks(int month, int year)
    {
        Calendar time = Calendar.getInstance();
        time.set(year, month-1, 1);
        int currentMonth = month-1;
        int start = -1;
        int end = -1;
        String period = "";
        List<String> periods = new ArrayList<String>();
        while (currentMonth == (month-1))
        {
            if ((start == -1) && ((time.get(Calendar.DAY_OF_WEEK)!= Calendar.SATURDAY) && (time.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)))
            {
                start = time.get(Calendar.DAY_OF_MONTH);
            }
            
            if ((time.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY))
            {
                end = time.get(Calendar.DAY_OF_MONTH);
                period = Integer.toString(start) + "/" + Integer.toString(month) + "-" + Integer.toString(end) + "/" + Integer.toString(month);
                periods.add(period);
                start = -1; end = -1;
            }
            time.add(Calendar.DAY_OF_MONTH, 1);
            currentMonth = time.get(Calendar.MONTH);
        }
        
        if ((start != -1) && (end == -1))
        {
            time.add(Calendar.DAY_OF_MONTH, -1);
            end = time.get(Calendar.DAY_OF_MONTH);
            period = Integer.toString(start) + "/" + Integer.toString(month) + "-" + Integer.toString(end) + "/" + Integer.toString(month);
            periods.add(period);            
        }
        return periods;
    }
    
    public List<PlannedWeeklyDemand> getPlannedWeeklyDemands(String month) {
        Query q = em.createQuery("SELECT p FROM PlannedMonthlyDemand p WHERE p.monthName =:month");
        q.setParameter("month", month);
        PlannedMonthlyDemand p = (PlannedMonthlyDemand) q.getSingleResult();
        List<PlannedWeeklyDemand> list = p.getListOfPlannedWeeklyDemand();
        return list;
    }
    
    public PlannedMonthlyDemand getNextMonth(String month)
    {
        int nextMonth = -1;
        int nextYear = -1;
        int monthNumber = Integer.parseInt(month.substring(0, month.length() - 5));
        int year = Integer.parseInt(month.substring(month.length() - 4));
        
        if (monthNumber == 12)
        {
            nextMonth = 1;
            nextYear = year + 1;
        }
        else if (monthNumber < 12)
        {
            nextMonth = monthNumber + 1;
            nextYear = year;
        }
        String monthString = Integer.toString(nextMonth) + "/" + Integer.toString(nextYear);
        
        //PlannedMonthlyDemand result = em.find(PlannedMonthlyDemand.class, monthString);
         Query q = em.createQuery("SELECT p from PlannedMonthlyDemand p WHERE p.monthName =:monthString");
         q.setParameter("monthString", monthString);
         PlannedMonthlyDemand result = (PlannedMonthlyDemand) q.getSingleResult();
        return result;
    }
    
    public PlannedWeeklyDemand getFirstWeekNextMonth(String month)
    {
        PlannedMonthlyDemand plannedMonthlyDemand = this.getNextMonth(month);
        List<PlannedWeeklyDemand> weekList = plannedMonthlyDemand.getListOfPlannedWeeklyDemand();
        if (!weekList.isEmpty())
        {
            return weekList.get(0);
        }
            
        return null;
    }
}
